package kassiopeia.gui

import java.io.Serializable;
import kassiopeia.gui.task.Connection;
import kassiopeia.gui.task.Plugin;
import kassiopeia.gui.task.Task;

class TaskDatabaseService {

    static transactional = true

    def deleteTaskByName(String taskName) {
        Task task = Task.findByName(taskName)
        if(!task) { return false }
        task.delete()
        return true
    }

    def getAllTasks() {
        Task.list()
    }

    def saveTask(Task task) {
        task.save()
    }

    def getTaskByName(String taskName) {
        if(taskName) {
            Task.findByName(taskName)
        } else {
            null
        }
    }

    def getPluginById(String taskName, String instanceId) {
        def task = Task.findByName(taskName)
        for(Plugin plugin in task.plugins) {
            if(plugin.instanceId.equals(instanceId)) { return plugin }
        }
    }

    def savePlugin(String taskName, Plugin plugin) {
       plugin.task = Task.findByName(taskName)
       plugin.save()
    }

    def deletePlugin(String taskName, String instanceId) {
        Task task = Task.findByName(taskName)
        if(!task) { return false }

        def toRemove = []
        for(Connection c in task.connections) {
            if(c.fromInstanceId.equals(instanceId) || c.toInstanceId.equals(instanceId)) {
                toRemove.add(c)
            }
        }

        toRemove.each { connection ->
            task.removeFromConnections(connection)
            connection.delete()
        }

        Plugin plugin = Plugin.findByInstanceId(instanceId)
        if(!plugin) { return false }
        task.removeFromPlugins(plugin)
        plugin.delete()
        return true
    }

    def saveConnection(String taskName,Connection connection) {
        Task task = Task.findByName(taskName)
        if(!task) { return false }
        //task.addToConnections(connection)
        connection.task = task
        connection.save()
    }

    def deleteConnection(String taskName,Connection connection) {
        Task task = Task.findByName(taskName)
        if(!task) { return false }
        for(Connection c in task.connections) {
            if(c.fromInstanceId.equals(connection.fromInstanceId) || c.toInstanceId.equals(connection.toInstanceId)
                || c.fromOutputId.equals(connection.fromOutputId)) {
                task.removeFromConnections(c)
                c.delete()
                return true
            }
        }
        return false
    }
}
